﻿using HuaCheng.Model;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace HuaCheng.Controller
{
    public class SerializableControl
    {
        /// <summary>
        /// 将对象序列化为二进制
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static byte[] SerializeToBinary(object obj)
        { 
            MemoryStream stream = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(stream, obj);
            byte[] data = stream.ToArray();
            stream.Close();
            return data;
        }
        /// <summary>
        /// 将二进制反序列化为对象
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static object DeserializeWithBinary(byte[] data)
        {
            MemoryStream stream = new MemoryStream();
            stream.Write(data, 0, data.Length);
            stream.Position = 0;
            BinaryFormatter bf = new BinaryFormatter();
            object obj = bf.Deserialize(stream);
            stream.Close();
            return obj;
        }
        /// <summary>
        /// 将二进制存入文件
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="savePath"></param>
        public static void SaveBinary(byte[] bytes, string savePath)
        {
            FileStream fs = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write);
            fs.Write(bytes, 0, bytes.Length);
            fs.Close();
        }
        /// <summary>
        /// 从文件中读取二进制
        /// </summary>
        /// <param name="savePath"></param>
        /// <returns></returns>
        public static byte[] LoadBinary(string savePath)
        {
            FileStream fs = new FileStream(savePath, FileMode.Open);
            long size = fs.Length;
            byte[] arr = new byte[size];
            fs.Read(arr, 0, arr.Length);
            fs.Close();
            return arr;
        }
    }
}
